package com.tgpms.web.element.service.impl;

import java.math.BigDecimal;
import java.util.Date;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tgpms.common.Result;
import com.tgpms.exception.ExceptionExplain;
import com.tgpms.interfaces.dto.VformInterface;
import com.tgpms.util.Common;
import com.tgpms.util.PageInfo;
import com.tgpms.util.VformBeanUtil;
import com.tgpms.web.element.dao.CommodityMasterMapper;
import com.tgpms.web.element.dao.WsElementMapper;
import com.tgpms.web.element.dto.D1120Dto;
import com.tgpms.web.element.entity.CommodityMaster;
import com.tgpms.web.element.entity.WsElement;
import com.tgpms.web.element.service.ICommodityMasterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jl
 * @since 2020-07-07
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, rollbackFor = Exception.class)
public class CommodityMasterServiceImpl implements ICommodityMasterService {

    @Resource
    private CommodityMasterMapper mapper;
    @Autowired
    private VformInterface vformInterface;
    @Autowired
    private WsElementMapper wsElementMapper;

    /**
     * 新增
     */
    @Override
    public Map<String, String> addCommodityMaster(CommodityMaster en) {
        Map<String, String> map = new HashMap<String, String>();
        //对象转json字符串, 字段驼峰转下划线大写字段
        JSONObject json = VformBeanUtil.entityToJsonString(en);
        if (json.isEmpty()) {
            map.put("code", "-2");
            map.put("info", ExceptionExplain.ERROR_BY_PARSING.getExplain());
            return map;
        }
//		System.out.println("vform增加上送参数   "+json.toString());
        //vform同步插入
        Result result = vformInterface.insert("D1120", json);
//		System.out.println("vform增加返回结果   "+result);
        if (result == null || !result.getSuccess()) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            return map;
        }
        String resData = result.getData().toString();
        if (resData.equals("{\"message\":\"login\"}")) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
            return map;
        }
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
            map.put("code", "-4");
            map.put("info", reJson.get("validateError").toString());
            return map;
        } else {
            map.put("code", "1");
            map.put("info", ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
        }
        return map;
    }

    /**
     * 更新
     */
    @Override
    public Map<String, String> updateCommodityMaster(CommodityMaster en) {
        Map<String, String> map = new HashMap<String, String>();
        JSONObject keyjson = new JSONObject();
        keyjson.put("QUICK_CODE", en.getQuickCode());
        JSONObject pajson = VformBeanUtil.entityToJsonStringByUpdate(en);
        pajson.remove("QUICK_CODE");

//        System.out.println("vform更新上送主键   "+keyjson.toString());
//        System.out.println("vform更新上送参数   "+pajson.toString());
        //vform同步更新
        Result result = vformInterface.update("D1120", keyjson.toString(), pajson.toString(), null, null, null);
//        System.out.println("vform更新返回结果   "+result);
        if (result == null || !result.getSuccess()) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            return map;
        }
        String resData = result.getData().toString();
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
            map.put("code", "-4");
            map.put("info", reJson.get("validateError").toString());
            return map;
        } else {
            map.put("code", "1");
            map.put("info", ExceptionExplain.SUCCESS_BY_UPDATE.getExplain());
        }
        return map;
    }

    /**
     * 根据主键删除
     */
    @Override
    public Map<String, String> deleteCommodityMaster(Integer quickCode) {
        Result findResult = vformInterface.find("D1120","{\"QUICK_CODE=\":\""+quickCode+"\"}","1","1","N","N","");
        Map<String, String> map = new HashMap<String, String>();
        JSONObject keyjson = new JSONObject();
        keyjson.put("QUICK_CODE", quickCode);
        System.out.println("vform删除上送主键   " + keyjson.toString());
        //vform同步删除
        Result result = vformInterface.delete("D1120", keyjson.toJSONString());
        System.out.println("vform删除返回结果   " + result);
        if (result == null || !result.getSuccess()) {
            map.put("code", "-3");
            map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
            return map;
        }
        String resData = result.getData().toString();
        JSONObject reJson = JSONObject.parseObject(resData);
        if (reJson.get("status").toString().equals("error")) {
            map.put("code", "-4");
            map.put("info", reJson.get("validateError").toString());
            return map;
        } else {
            // 删除物资属性
            List<Map<String,String>> list = JSONArray.parseObject(findResult.getData().toString(), List.class);
            if (CollUtil.isNotEmpty(list)) {
                Map<String, String> stringStringMap = list.get(0);
                String commodityNumber = stringStringMap.get("COMMODITY_NUMBER");
                wsElementMapper.delete(new QueryWrapper<WsElement>().eq("COMMODITY_NUMBER",commodityNumber));
            }
            map.put("code", "1");
            map.put("info", ExceptionExplain.SUCCESS_BY_DELETE.getExplain());
        }
        return map;
    }

    @Override
    public Result selCommodityMasterList(PageInfo pageInfo) {
        JSONObject param = new JSONObject();
        Object selparam = pageInfo.getQueryMap().get("selparam");
        Object leftdition = pageInfo.getQueryMap().get("leftdition");
        Object condition = pageInfo.getQueryMap().get("condition");
        Object dataowner = pageInfo.getQueryMap().get("dataowner");
        if (Common.isEmpty(selparam)) {
            param.put("[SQL1]", " ");
        } else {
            param.put("[SQL1]", selparam.toString());
        }
        if (Common.isEmpty(leftdition)) {
            param.put("[SQL2]", " ");
        } else {
            param.put("[SQL2]", leftdition.toString());
        }
        if (Common.isEmpty(condition)) {
            param.put("[SQL3]", " ");
        } else {
            param.put("[SQL3]", condition.toString());
        }
        Result result = vformInterface.multiForMsQueryBySql("SCWZC036", param.toJSONString(), pageInfo.getPage(),
                pageInfo.getSize(), "Y", "Y", dataowner.toString());
        return result;
    }

    @Override
    public Map<String, String> batchImport(MultipartFile file,String dataOwner, String insertName) {
        Map<String, String> map = new HashMap<>();

        ExcelReader reader;
        try {
            InputStream inputStream = file.getInputStream();
            reader = ExcelUtil.getReader(inputStream);

            List<D1120Dto> all = reader.readAll(D1120Dto.class);
            List<CommodityMaster> collect = all.stream().map(e -> {
                CommodityMaster commodityMaster = new CommodityMaster();
                commodityMaster.setCommodityTypeCode(e.getCOMMODITY_TYPE_CODE());
                commodityMaster.setCommodityNumber(e.getCOMMODITY_NUMBER());
                commodityMaster.setUnitOfMeasure(e.getUNIT_OF_MEASURE());
                commodityMaster.setUseMatrixFlag("N");
                commodityMaster.setShortDesc(e.getSHORT_DESC());
                commodityMaster.setModifyDate(DateUtil.now());
                commodityMaster.setLongDesc(e.getLONG_DESC());
                if (StrUtil.isNotBlank(dataOwner)) {
                    commodityMaster.setDataOwner(dataOwner);
                }
                commodityMaster.setInsertUser(insertName);
                commodityMaster.setInsertDate(DateUtil.now());
                return commodityMaster;
            }).collect(Collectors.toList());

            JSONArray jsonArray = new JSONArray();
            collect.forEach(e -> {
                //对象转json字符串, 字段驼峰转下划线大写字段
                JSONObject json = VformBeanUtil.entityToJsonString(e);
                jsonArray.add(json);
            });
            //vform同步插入
            Result result = vformInterface.insertBatch("D1120", jsonArray);
            if (result == null || !result.getSuccess()) {
                map.put("code", "-3");
                map.put("info", ExceptionExplain.ERROR_BY_VFORM_POST.getExplain());
                return map;
            }
            String resData = result.getData().toString();
            if (resData.equals("{\"message\":\"login\"}")) {
                map.put("code", "-3");
                map.put("info", ExceptionExplain.ERROR_BY_OVERDUE.getExplain());
                return map;
            }
            JSONObject reJson = JSONObject.parseObject(resData);
            if (reJson.get("status").toString().equals("error")) {
                map.put("code", "-4");
                map.put("info", reJson.get("validateError").toString());
                return map;
            } else {
                map.put("code", "1");
                map.put("info", ExceptionExplain.SUCCESS_BY_INSERT.getExplain());
                map.put("data", "批量数据新增成功");
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;

    }
}
